package com.sptus.web.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sptus.common.core.domain.AjaxResult;
import com.sptus.common.core.domain.model.LoginUser;
import com.sptus.common.utils.SecurityUtils;
import com.sptus.framework.annotation.AutoLog;
import com.sptus.framework.query.QueryGenerator;
import com.sptus.framework.service.BaseCommonService;
import com.sptus.framework.utils.CustomSortExample;
import com.sptus.system.domain.DevDictionaries;
import com.sptus.system.domain.DevInfoMsg1;
import com.sptus.system.domain.Equipment;
import com.sptus.system.domain.vo.AppInfo;
import com.sptus.system.service.IDevInfoMsg1Service;
import com.sptus.system.service.ISptDevLogService;
import com.sptus.system.domain.vo.AppDataVo;
import com.sptus.web.config.DataLoaderConfig;
import com.sptus.web.entity.SptUser;
import com.sptus.web.service.*;
import com.sptus.web.service.impl.DevDictionariesServiceImpl;
import com.sptus.web.util.DevSqlUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Api(tags="equipment")
@RestController
@RequestMapping("/devDictionaries/equipment")
@Slf4j
public class EquipmentController  {
   @Autowired
   private CloudIEquipmentService equipmentService;

   @Autowired
   DataLoaderConfig dataLoaderConfig;

    @Autowired
    IDevInfoMsg1Service msg1Service;

    @Autowired
    ISptUserEquipmentService sptUserEquipmentService;

    @Autowired
    ISptUserParentService sptUserParentService;

    @Autowired
    private ISptDevLogService sptDevLogService;


    @Resource
    private BaseCommonService baseCommonService;

    @PreAuthorize("@ss.hasPermi('device:Parameter')")
    @PostMapping("postDevParameter")
    @ApiOperation(value = "设置", notes = "setMsg")
    public AjaxResult setDevParameter(@RequestBody AppInfo appInfo) {
        LambdaQueryWrapper<Equipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(Equipment::getSn,appInfo.getSn());
        Equipment equipment = equipmentService.getBaseMapper().selectOne(equipmentLambdaQueryWrapper);
        if (StringUtils.isEmpty(equipment)) {
            return AjaxResult.error("Please enter correctly sn");
        }
        if (!equipment.getStatus().equals("1")) {
            return AjaxResult.error("Device Offline");
        }
        ArrayList<DevDictionaries> devs = appInfo.getDevs();
        //设置参数
        if (StringUtils.isEmpty(equipment.getMac())) {
            return AjaxResult.error("Device Offline");
        }

        HashMap<String, Object> stringObjectHashMap = verifyValue(appInfo.getSn(), appInfo.getCode(), appInfo.getValue());
        boolean equals = stringObjectHashMap.get("verify").equals(true);
        if(equals){
            DevDictionaries devDictionaries1 = new DevDictionaries();
            devDictionaries1.setName(appInfo.getSetName());
            devDictionaries1.setValue(appInfo.getValue());
            devDictionaries1.setSN(appInfo.getSn());
            devDictionaries1.setCode( appInfo.getCode());
            sptDevLogService.saveDevSet(devDictionaries1,"1");
            LoginUser user= (LoginUser) SecurityUtils.getLoginUser();
//			 DevSqlUtil.setDevParameters(appInfo.getCode(), appInfo.getValue(), equipment.getMac(),appInfo.getSn(),baseCommonService,"pc:->"+user.getId(),user.getEmail());
            updateValue(appInfo.getSn(), appInfo.getCode(), appInfo.getValue());
            return AjaxResult.success();
        }else {
            return AjaxResult.error(stringObjectHashMap.get("msg")+"", stringObjectHashMap);
        }
    }


    public void  updateValue(String sn,String code,String value){
        if(code.equals("RL")){
            LambdaQueryWrapper<DevInfoMsg1> qw=new LambdaQueryWrapper();
            qw.eq(DevInfoMsg1::getSn,sn);
            DevInfoMsg1 devInfoMsg1 = new DevInfoMsg1();
            if (value.indexOf(0) ==0){  devInfoMsg1.setRl(value.substring(1));}else {
                devInfoMsg1.setRl(value);
            }

            msg1Service.update(devInfoMsg1,qw);
        }
    }
    public  HashMap<String, Object> verifyValue(String sn,String code,String value){
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        ArrayList<DevDictionaries> devDictionaries = new ArrayList<>();
        ArrayList<HashMap<String, String>> hashMaps = new ArrayList<>();
        HashMap<String, String> codes = new HashMap<>();
        stringStringHashMap.put("verify",true);
        //13 14
        if(code.equals("SP")){
            DevDictionaries devDictionaries1 = new DevDictionaries();
            devDictionaries1.setName("13 Operation Mode");
            devDictionaries1.setCode("RL");
            devDictionaries1.setRelevanceTable("dev_info_msg1");
            devDictionaries1.setDataType(1);
            devDictionaries1.setDescription("Refer to Section 12 for the detailed operation");
            devDictionaries1.setClassify(2 + "");
            devDictionaries1.setState(1 + "");
            devDictionaries.add(devDictionaries1);
            List<DevDictionaries> devDictionariesList = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, sn);
            DevDictionaries devDictionariesRL = devDictionariesList.get(0);
            String valueRL = devDictionariesRL.getValue().split(" ")[0];
            if(!valueRL.equals("77")){
                stringStringHashMap.put("verify",false);
                stringStringHashMap.put("msg","please select 13 HBD");
                codes.put("RL","077");
                hashMaps.add(codes);
                stringStringHashMap.put("codes",hashMaps);
            }
        }
        //01,02,40关联
        if(code.equals("SP")){
            DevDictionaries devDictionaries1 = new DevDictionaries();
            devDictionaries1.setName("13 Operation Mode");
            devDictionaries1.setCode("RL");
            devDictionaries1.setRelevanceTable("dev_info_msg1");
            devDictionaries1.setDataType(1);
            devDictionaries1.setDescription("Refer to Section 12 for the detailed operation");
            devDictionaries1.setClassify(2 + "");
            devDictionaries1.setState(1 + "");
            devDictionaries.add(devDictionaries1);
            List<DevDictionaries> devDictionariesList = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, sn);
            DevDictionaries devDictionariesRL = devDictionariesList.get(0);
            String valueRL = devDictionariesRL.getValue().split(" ")[0];
            if(!valueRL.equals("77")){
                stringStringHashMap.put("verify",false);
                stringStringHashMap.put("msg","please select 13 HBD");
                codes.put("RL","077");
                hashMaps.add(codes);
                stringStringHashMap.put("codes",hashMaps);
            }
        }



        return stringStringHashMap;
    }
    @GetMapping("getDevParameter")
    @ApiOperation(value = "设置参数回显", notes = "setMsg")
    public AjaxResult getDevParameter(AppInfo appInfo, SptUser sptUser) {
        // todo 首页真实数据返回
        if (StringUtils.isEmpty(appInfo.getSn())) {
            return AjaxResult.error("please enter sn");
        }
        ArrayList<AppDataVo> appDataVos = dataLoaderConfig.loadData(appInfo.getSn(),"new");
        //todo 获取参数数据
        return AjaxResult.success(appDataVos);
    }

   /**
    * 分页列表查询
    *
    * @param equipment
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   //@AutoLog(value = "equipment-分页列表查询")
   @ApiOperation(value="equipment-分页列表查询", notes="equipment-分页列表查询")
   @GetMapping(value = "/list")
   public AjaxResult queryPageList(Equipment equipment,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {

       QueryWrapper<Equipment> queryWrapper = QueryGenerator.initQueryWrapper(equipment, req.getParameterMap());
       Page<Equipment> page = new Page<Equipment>(pageNo, pageSize);
       IPage<Equipment> pageList = equipmentService.page(page, queryWrapper);
       return AjaxResult.success(pageList);
   }

   /**
    *   添加
    *
    * @param equipment
    * @return
    */
   @AutoLog(value = "equipment-添加")
   @ApiOperation(value="equipment-添加", notes="equipment-添加")
//	@RequiresPermissions("devDictionaries:equipment:add")
   @PostMapping(value = "/add")
   public AjaxResult add(@RequestBody Equipment equipment) {
       equipmentService.save(equipment);
       return AjaxResult.success("添加成功！");
   }

   /**
    *  编辑
    *
    * @param equipment
    * @return
    */
   @AutoLog(value = "equipment-编辑")
   @ApiOperation(value="equipment-编辑", notes="equipment-编辑")
   //@RequiresPermissions("devDictionaries:equipment:edit")
   @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
   public AjaxResult edit(@RequestBody Equipment equipment) {
       equipmentService.updateById(equipment);
       return AjaxResult.success("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "equipment-通过id删除")
   @ApiOperation(value="equipment-通过id删除", notes="equipment-通过id删除")
//   @RequiresPermissions("devDictionaries:equipment:delete")
   @DeleteMapping(value = "/delete")
   public AjaxResult delete(@RequestParam(name="id",required=true) String id) {
       equipmentService.removeById(id);
       return AjaxResult.success("删除成功!");
   }
   @Autowired
   DevDictionariesServiceImpl devDictionariesService;
   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "equipment-批量删除")
   @ApiOperation(value="equipment-批量删除", notes="equipment-批量删除")
//   @RequiresPermissions("devDictionaries:equipment:deleteBatch")
   @DeleteMapping(value = "/deleteBatch")
   public AjaxResult deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.equipmentService.removeByIds(Arrays.asList(ids.split(",")));
       return AjaxResult.success("批量删除成功!");
   }


    @Autowired
    private JdbcTemplate jdbcTemplate;
    @AutoLog(value = "设备详情数据")
    @ApiOperation(value="设备详情数据", notes="equipment-批量删除")
    @GetMapping(value = "/equipmentDataInfo")
    public AjaxResult equipmentDataInfo( DevDictionaries  dev) {
        LambdaQueryWrapper<DevDictionaries> devDictionariesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        devDictionariesLambdaQueryWrapper.in(!ObjectUtils.isEmpty(dev.getIds()),DevDictionaries::getId, dev.getIds());
        devDictionariesLambdaQueryWrapper.eq(DevDictionaries::getState, "1");
        List<DevDictionaries> devDictionaries = devDictionariesService.getBaseMapper().selectList(devDictionariesLambdaQueryWrapper);
        //通过字典获取设备数据
        AppInfo appInfo = new AppInfo();
        appInfo.setSn(dev.getSN());
        devDictionaries = DevSqlUtil.DevDataSql(devDictionaries, jdbcTemplate, dev.getSN());
        return AjaxResult.success("获取成功", devDictionaries);
    }
    @AutoLog(value = "设备电池详情数据")
    @ApiOperation(value="设备电池详情数据", notes="设备电池详情数据")
    @GetMapping(value = "/equipmentBatteryDataInfo")
    public AjaxResult equipmentBatteryDataInfo( DevDictionaries  dev) {
        AppInfo appInfo = new AppInfo();
        appInfo.setSn(dev.getSN());
        HashMap<String, ArrayList<DevDictionaries>> allData = devDictionariesService.getAllData(appInfo);
        return AjaxResult.success("获取成功", allData);
    }

    @AutoLog(value = "设备字典详情数据")
    @ApiOperation(value="设备字典详情数据", notes="设备字典详情数据")
    @GetMapping(value = "/devDictionaries")
    public AjaxResult devDictionaries() {
        LambdaQueryWrapper<DevDictionaries> devDictionariesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        devDictionariesLambdaQueryWrapper.eq(DevDictionaries::getState,"1");
        List<DevDictionaries> devDictionaries = devDictionariesService.getBaseMapper().selectList(devDictionariesLambdaQueryWrapper);
        devDictionaries = CustomSortExample.sort(devDictionaries);
        return AjaxResult.success("获取成功", devDictionaries);
    }


    @GetMapping("/getHistoryData")
    @ApiOperation(value="获取历史数据接口", notes="获取历史数据接口")
    public AjaxResult getHistoryData(DevDictionaries  dev,AppInfo appInfo) throws ParseException {
        if(StringUtils.isEmpty(appInfo.getEndTime())&& !StringUtils.isEmpty(appInfo.getStartTime())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = sdf.parse(appInfo.getStartTime());
            long time = parse.getTime();
            long end= time+24*60*60*1000;
            String format1 = sdf.format(end);
            appInfo.setEndTime(format1);
        }

        if(StringUtils.isEmpty(dev.getIds())|| StringUtils.isEmpty(appInfo.getStartTime())|| StringUtils.isEmpty(appInfo.getEndTime())){
            return AjaxResult.success("参数未输入");
        }
        LambdaQueryWrapper<DevDictionaries> devDictionariesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        devDictionariesLambdaQueryWrapper.in(DevDictionaries::getId, dev.getIds());
        devDictionariesLambdaQueryWrapper.eq(DevDictionaries::getState, "1");
        List<DevDictionaries> devDictionaries = devDictionariesService.getBaseMapper().selectList(devDictionariesLambdaQueryWrapper);
        for (DevDictionaries devDictionary : devDictionaries) {
//			 devDictionary.setAnalysis("");
            devDictionary.setRelevanceTable(devDictionary.getRelevanceTable()+"_history");

        }
//		     ArrayList<String> strings = new ArrayList<>();
            DevDictionaries devDictionariesTime = new DevDictionaries();
            devDictionariesTime.setCode("DATE_FORMAT(create_time,'%y/%m/%e %H:%i')");
            devDictionariesTime.setRelevanceTable("dev_info_msg0_history");
            devDictionaries.add(devDictionariesTime);
            devDictionaries = DevSqlUtil.DevDataHistorySql(devDictionaries, appInfo.getStartTime(), appInfo.getEndTime(), jdbcTemplate, appInfo.getSn());

        return AjaxResult.success(devDictionaries);
    }
   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "equipment-通过id查询")
   @ApiOperation(value="equipment-通过id查询", notes="equipment-通过id查询")
   @GetMapping(value = "/queryById")
   public AjaxResult queryById(@RequestParam(name="id",required=true) String id) {
       Equipment equipment = equipmentService.getById(id);
       if(equipment==null) {
           return AjaxResult.error("未找到对应数据");
       }
       return AjaxResult.success(equipment);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param equipment
   */
   /*@RequiresPermissions("devDictionaries:equipment:exportXls")
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, Equipment equipment) {
       return super.exportXls(request, equipment, Equipment.class, "equipment");
   }*/

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   /*@RequiresPermissions("devDictionaries:equipment:importExcel")
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, Equipment.class);
   }*/

}
